import React, { useState, useEffect } from 'react';
import { PageContainer } from '@ant-design/pro-components';
import { Form, Input, Button, Card, message, Select, TreeSelect, InputNumber, Switch, Space } from 'antd';
import { history, useLocation } from 'umi';
import {
  MenuOutlined,
  AppstoreOutlined,
  FileOutlined,
  FolderOutlined,
  LinkOutlined,
  ArrowLeftOutlined,
} from '@ant-design/icons';

const { Option } = Select;
const { TextArea } = Input;

const MenuCreatePage: React.FC = () => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [menuType, setMenuType] = useState('M');
  const [treeData, setTreeData] = useState<any[]>([]);
  const location = useLocation();

  useEffect(() => {
    fetchMenuTree();
    // Set parent menu from state if exists
    if (location.state?.parentId) {
      form.setFieldsValue({ parentId: location.state.parentId });
    }
  }, [location.state]);

  const fetchMenuTree = async () => {
    try {
      // TODO: Replace with actual API call
      // const response = await fetch('/api/menus/tree');
      // const data = await response.json();
      
      // Mock data for now
      const mockData = [
        {
          id: '0',
          name: '根目录',
          children: [
            {
              id: '1',
              name: '系统管理',
              type: 'M',
              children: [
                { id: '2', name: '用户管理', type: 'C' },
                { id: '3', name: '角色管理', type: 'C' },
                { id: '4', name: '菜单管理', type: 'C' },
                { id: '5', name: '权限管理', type: 'C' },
              ],
            },
          ],
        },
      ];
      
      setTreeData(mockData);
    } catch (error) {
      message.error('获取菜单树失败');
    }
  };

  const onFinish = async (values: any) => {
    setLoading(true);
    try {
      // TODO: Replace with actual API call
      // await fetch('/api/menus', {
      //   method: 'POST',
      //   headers: {
      //     'Content-Type': 'application/json',
      //   },
      //   body: JSON.stringify(values),
      // });
      
      message.success('菜单创建成功');
      history.push('/menu/list');
    } catch (error) {
      message.error('菜单创建失败');
    } finally {
      setLoading(false);
    }
  };

  const handleTypeChange = (value: string) => {
    setMenuType(value);
  };

  const renderIconSelect = () => (
    <Select
      showSearch
      placeholder="选择图标"
      optionFilterProp="children"
      filterOption={(input, option) =>
        (option?.children as unknown as string).toLowerCase().includes(input.toLowerCase())
      }
    >
      <Option value="DashboardOutlined">
        <Space>
          <MenuOutlined /> Dashboard
        </Space>
      </Option>
      <Option value="SettingOutlined">
        <Space>
          <MenuOutlined /> 系统设置
        </Space>
      </Option>
      <Option value="UserOutlined">
        <Space>
          <MenuOutlined /> 用户
        </Space>
      </Option>
      <Option value="TeamOutlined">
        <Space>
          <MenuOutlined /> 团队
        </Space>
      </Option>
      <Option value="LockOutlined">
        <Space>
          <MenuOutlined /> 权限
        </Space>
      </Option>
      <Option value="MenuOutlined">
        <Space>
          <MenuOutlined /> 菜单
        </Space>
      </Option>
    </Select>
  );

  return (
    <PageContainer
      header={{
        title: '新建菜单',
        breadcrumb: {
          items: [
            { title: '系统管理' },
            { title: '菜单管理', path: '/menu/list' },
            { title: '新建菜单' },
          ],
        },
      }}
    >
      <Card>
        <Button 
          type="text" 
          icon={<ArrowLeftOutlined />} 
          onClick={() => history.goBack()}
          style={{ marginBottom: 16 }}
        >
          返回
        </Button>
        
        <Form
          form={form}
          layout="vertical"
          onFinish={onFinish}
          initialValues={{
            type: 'C',
            visible: true,
            status: 1,
            sort: 0,
          }}
        >
          <Form.Item
            name="parentId"
            label="上级菜单"
            rules={[{ required: true, message: '请选择上级菜单' }]}
          >
            <TreeSelect
              treeData={treeData}
              placeholder="请选择上级菜单"
              fieldNames={{ label: 'name', value: 'id', children: 'children' }}
              treeDefaultExpandAll
              allowClear
            />
          </Form.Item>

          <Form.Item
            name="type"
            label="菜单类型"
            rules={[{ required: true, message: '请选择菜单类型' }]}
          >
            <Select onChange={handleTypeChange}>
              <Option value="M">
                <Space>
                  <AppstoreOutlined /> 目录
                </Space>
              </Option>
              <Option value="C">
                <Space>
                  <MenuOutlined /> 菜单
                </Space>
              </Option>
              <Option value="F">
                <Space>
                  <FileOutlined /> 按钮
                </Space>
              </Option>
            </Select>
          </Form.Item>

          <Form.Item
            name="name"
            label="菜单名称"
            rules={[{ required: true, message: '请输入菜单名称' }]}
          >
            <Input placeholder="请输入菜单名称" />
          </Form.Item>

          {menuType !== 'F' && (
            <Form.Item
              name="path"
              label="路由地址"
              rules={[{ required: menuType !== 'F', message: '请输入路由地址' }]}
            >
              <Input placeholder="如：/system/user" />
            </Form.Item>
          )}

          {menuType === 'F' && (
            <Form.Item
              name="permission"
              label="权限标识"
              rules={[{ required: true, message: '请输入权限标识' }]}
            >
              <Input placeholder="如：system:user:add" />
            </Form.Item>
          )}

          <Form.Item
            name="icon"
            label="图标"
            hidden={menuType === 'F'}
          >
            {renderIconSelect()}
          </Form.Item>

          <Form.Item
            name="sort"
            label="显示排序"
            rules={[{ required: true, message: '请输入显示排序' }]}
          >
            <InputNumber min={0} style={{ width: '100%' }} />
          </Form.Item>

          <Form.Item
            name="visible"
            label="显示状态"
            valuePropName="checked"
          >
            <Switch
              checkedChildren="显示"
              unCheckedChildren="隐藏"
              defaultChecked
            />
          </Form.Item>

          <Form.Item
            name="status"
            label="状态"
            valuePropName="checked"
          >
            <Switch
              checkedChildren="启用"
              unCheckedChildren="停用"
              defaultChecked
            />
          </Form.Item>

          <Form.Item name="remark" label="备注">
            <TextArea rows={4} placeholder="请输入备注信息" />
          </Form.Item>

          <Form.Item>
            <Button type="primary" htmlType="submit" loading={loading}>
              提交
            </Button>
            <Button
              style={{ marginLeft: 8 }}
              onClick={() => history.goBack()}
              disabled={loading}
            >
              取消
            </Button>
          </Form.Item>
        </Form>
      </Card>
    </PageContainer>
  );
};

export default MenuCreatePage;
